#include<iostream>

struct ListNode {
    int val;
    ListNode *next;

    ListNode() : val(0), next(nullptr) {}

    ListNode(int x) : val(x), next(nullptr) {}

    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution61 {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        if (head == nullptr || head->next == NULL || k == 0)return head;
        int count = 0;
        ListNode *tmp_count_node = head;
        while (tmp_count_node != NULL) {
            count++;
            tmp_count_node = tmp_count_node->next;
        }
        k = k % count;
        if (k == 0)return head;
        ListNode *tmp_head = new ListNode();
        tmp_head->next = head;
        ListNode *fast = tmp_head, *slow = tmp_head;
        while (k--) fast = fast->next;
        while (fast->next) {
            fast = fast->next;
            slow = slow->next;
        }
        ListNode *tmp = tmp_head->next;
        tmp_head->next = slow->next;
        slow->next = NULL;
        fast->next = tmp;
        return tmp_head->next;
    }
};